<template>
    <el-dialog v-model="showExcelPreview" title="" fullscreen :show-close="false" destroy-on-close @open="renderHtml">
        <!-- 自定义标题 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">Excel 预览</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <!--  -->
        <div ref="excelContainer" id="excel-preview"></div>
    </el-dialog>
</template>

<script setup lang="ts">
import { CircleCloseFilled } from '@element-plus/icons-vue';
import * as XLSX from 'xlsx';

// 自定义model
const showExcelPreview = defineModel('showExcelPreview', { default: false, type: Boolean, required: true });
// Excel 数据
const props = defineProps<{
    excelData: ArrayBuffer | undefined;
}>();
// 表格ref
const excelContainer = ref<HTMLElement | undefined>();

// 监听showExcelPreview变化
watch(
    () => showExcelPreview.value,
    () => {
        if (showExcelPreview.value) {
            renderHtml();
        }
    }
);

// 渲染html
const renderHtml = () => {
    // 解析文件
    const wb = XLSX.read(props.excelData);
    // 得到第一个工作表
    const ws = wb.Sheets[wb.SheetNames[0]];
    // id为excel-preview的元素
    const html = XLSX.utils.sheet_to_html(ws, {
        id: 'excel',
    });

    if (!excelContainer.value) {
        return;
    }
    excelContainer.value.innerHTML = html;
};
</script>

<style scoped lang="scss">
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
</style>
